<template>
	<view class="main">
		<Header
			:title="t('management.cleaningPlan')"
			:showRight="isSelect"
			rightColor="#0084fc"
			:Righttext="t('save')"
			@rightClick="save" />
		<view v-if="cleaningTaskList.length && !isLoading">
			<up-list class="cell-list">
				<up-swipe-action>
					<up-list-item
						v-for="(item, index) in cleaningTaskList"
						:key="`item-${index}`">
						<up-swipe-action-item
							:options="options"
							@click="operateClick(item)">
							<up-cell @click="openDetail(item)">
								<template #icon>
									<view class="img-box">
										<up-avatar
											shape="square"
											size="36"
											src="/static/image/info/listIcon.png"
											customStyle="margin: 20px 10px"></up-avatar>
									</view>
								</template>
								<template #title>
									<view class="tilte-box">
										<view class="left">
											<up-text
												:text="item.plan_name"
												size="16"
												color="#333"
												bold></up-text>
											<up-text
												:text="`${t(
													'plan.createTime'
												)}：${parseTime(
													item.create_time
												)}`"
												style="margin-top: 10rpx"
												size="12"
												color="#999"></up-text>
										</view>
										<view class="right" v-if="isSelect">
											<up-avatar
												shape="square"
												size="48"
												v-if="checkedIndex == index"
												src="/static/image/device/circle-true.png"></up-avatar>
											<up-avatar
												shape="square"
												@click="checkedIndex = index"
												size="48"
												v-else
												src="/static/image/device/circle-false.png"></up-avatar>
										</view>
									</view>
								</template>
							</up-cell>
						</up-swipe-action-item>
					</up-list-item>
				</up-swipe-action>
			</up-list>
		</view>
		<view class="addBut" v-if="!isLoading">
			<up-icon
				@click="goAdd"
				name="plus-circle-fill"
				color="#0087fd"
				size="54"></up-icon>
		</view>
		<view class="loading" v-show="isLoading">
			<LoadingDots />
		</view>
		<up-empty
			v-if="!cleaningTaskList.length && !isLoading"
			icon="/static/image/common/noData.svg"
			width="35%"
			textSize="18"
			text-color="#b8b8b8"
			safeAreaInsetBottom
			:text="t('noList')"></up-empty>
		<TipsModal
			v-if="showTip"
			type="tip"
			:contentText="t('plan.info.delete')"
			@handleCancel="cancelTip"
			@handleConfirm="conformTip" />
		<up-popup
			:show="showDetail"
			@close="closeDetail"
			customStyle="width:100vw"
			mode="bottom">
			<view class="detail-box">
				<addTaskContentVue
					:device_sn="device_sn"
					:mapUrl="mapUrl"
					:detailInfo="detailInfo" />
			</view>
		</up-popup>
	</view>
</template>

<script setup lang="ts">
import Header from "@/components/header/index.vue";
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import LoadingDots from "@/components/LoadingDots/index.vue";
import addTaskContentVue from "./components/addTaskContent.vue";
import { delDevicePlanApi } from "@/service/index";
import TipsModal from "@/components/tipsModal/index.vue";
import { onMounted, ref, getCurrentInstance, reactive } from "vue";
import { useDevice } from "@/utils/device";
import { useDeviceStore } from "@/stores/device";
import moment from "moment-timezone";
import { onShow } from "@dcloudio/uni-app";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const isLoading = ref(false);
const device_sn = ref("");
const isSelect = ref(true);
const instance: any = getCurrentInstance();
const cleaningTaskList = ref<[]>([]);
const { getDeviceMaps } = useDevice();
const deviceStore = useDeviceStore();
const deviceMapList = ref<Plan[]>([]);
const checkedIndex = ref(-1);
const mapUrl = ref("");
const delId = ref("");
const mapId = ref("");
const showTip = ref(false);
const showDetail = ref(false);
const detailInfo: Plan = ref({});
const cancelTip = () => {
	showTip.value = false;
};
const mapStore: any = useUniversalStorage<string>("Map_Store", null);
const save = () => {};
const timeZoneStore = useUniversalStorage<string>(
	"SELECTED_TIMEZONE",
	"Asia/Shanghai"
);
const options = reactive([
	{
		text: t("delete"),
		style: {
			backgroundColor: "rgb(227, 77, 89)",
		},
	},
]);
const closeDetail = () => {
	showDetail.value = false;
};
const openDetail = (detail: Plan) => {
	detailInfo.value = detail.self_pattern;
	showDetail.value = true;
};
const init = async () => {
	isLoading.value = true;
	await getDeviceMaps(device_sn.value, "cleaningTask");
	mapStore.value = deviceStore.defaultDeviceMap;
	deviceMapList.value = deviceStore.deviceMapList;
	mapId.value = mapStore.value.map_info.map_id;
	mapUrl.value =
		deviceStore?.defaultDeviceMap?.map_info.map_docs[0].oss_url || "";
	cleaningTaskList.value = deviceStore.planList;
	isLoading.value = false;
};
onLoad((options) => {
	if (options?.device_sn) {
		device_sn.value = options.device_sn;
		isSelect.value = options.isSelect ? false : options.isSelect;
		init();
	}
});
onShow(() => {
	init();
});
const operateClick = (item: Plan) => {
	delId.value = item.planid;
	showTip.value = true;
};
const conformTip = async () => {
	const res = await delDevicePlanApi({
		device_sn: device_sn.value,
		planid: delId.value,
		map_id: mapId.value,
	});
	if (res.data.code === 0) {
		instance.proxy.$message(t("deleteOk"), "success");
		init();
	} else {
		instance?.proxy.$message(res.data.msg, "error");
	}
	showTip.value = false;
};
const fallbackFormat = (time: string | Date | null | undefined): string => {
	if (!time) return "";
	// 如果是 Date 对象，转换为 ISO 字符串
	const timeString = typeof time === "string" ? time : time.toISOString();
	// 移除 'T' 并截取前16个字符（去掉秒和时区信息）
	return timeString.replace(/T/g, " ").slice(0, 16);
};
const parseTime = (time: string | Date | null | undefined): string => {
	// 获取用户选择的时区
	const userTz: string | null = timeZoneStore.value;
	if (userTz) {
		try {
			// 使用 moment 解析 ISO 格式的时间字符串
			const create_time = time ? moment(time).tz(userTz) : null;
			return create_time ? create_time.format("YYYY-MM-DD HH:mm") : "";
		} catch (error) {
			console.error("时区转换失败:", error);
			return fallbackFormat(time);
		}
	} else {
		return fallbackFormat(time);
	}
};
const goAdd = () => {
	uni.navigateTo({
		url: `/pages/manage/cleaningTask/add?device_sn=${device_sn.value}`,
	});
};
//下拉刷新
onPullDownRefresh(() => {
	setTimeout(() => {
		init();
		uni.stopPullDownRefresh();
	}, 1500);
});
</script>

<style lang="scss" scoped>
.main {
	background-color: #fff;
	height: 100vh;
}
.loading {
	height: 100vh;
	background-color: #d8d8d8;
}
.cell-list {
	:deep(.u-cell__body) {
		padding: 0 10px !important;
	}
	:deep(.u-line) {
		border-bottom: 1px solid #e8e8e8 !important;
		margin-left: 10px !important;
	}
	.tilte-box {
		display: flex;
		justify-content: space-between;
		padding-right: 10px;
		align-items: center;
	}
}
.addBut {
	position: fixed;
	bottom: 10vh;
	right: 20px;
	width: 50px;
	z-index: 2;
}
:deep(.u-slide-up-enter-active) {
	/* #ifdef H5 */
	bottom: 0 !important;
	/* #endif */
}
:deep(.u-fade-enter-active) {
	/* #ifdef H5 */
	bottom: 0 !important;
	/* #endif */
}
.detail-box {
	// padding: 30rpx;
	// width: 100%;
	box-sizing: border-box;
	background: #fff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
}
</style>
